package com.usefullc.download.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.exception.BizException;
import com.usefullc.download.domain.Video;
import com.usefullc.download.enums.RegisterCodeStatusEnum;
import com.usefullc.download.enums.VideoStatusEnum;
import com.usefullc.download.mapper.VideoMapper;
import com.usefullc.download.param.CheckRegisterCodeParam;
import com.usefullc.download.param.VideoAnalyseParam;
import com.usefullc.download.query.VideoQuery;
import com.usefullc.download.vo.CheckRegisterCodeVo;
import com.usefullc.system.service.AbstractBizService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: Sampson
 * @date: 2022-03-27 15:29
 */
@Service
public class VideoService extends  AbstractBizService<VideoMapper, Video, VideoQuery> {

    @Autowired
    private RegisterCodeService registerCodeService;

//    @Override
//    public List<Predicate> getPredicates(Root<Video> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder, BaseQuery q) {
//        RegisterCodeQuery thisQuery = (RegisterCodeQuery) q;
//        List<Predicate> predicates = new ArrayList<>();
//        if (thisQuery.getDelState() != null) {
//            predicates.add(criteriaBuilder.equal(root.get("delState"), thisQuery.getDelState()));
//        }
//        if (thisQuery.getStatus() != null) {
//            predicates.add(criteriaBuilder.equal(root.get("status"), thisQuery.getStatus()));
//        }
//        if (StringUtils.isNotEmpty(thisQuery.getCode())) {
//            predicates.add(criteriaBuilder.equal(root.get("code"), thisQuery.getCode()));
//        }
//        if (StringUtils.isNotEmpty(thisQuery.getMachineId())) {
//            predicates.add(criteriaBuilder.equal(root.get("machineId"), thisQuery.getMachineId()));
//        }
//
//        return predicates;
//    }

    @Override
    protected QueryWrapper<Video> getQueryWrapper(VideoQuery query) {
        QueryWrapper<Video> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    @Transactional
    public Video analyse(VideoAnalyseParam param) {
        String machineId = param.getMachineId();
        CheckRegisterCodeParam checkRegisterCodeParam = new CheckRegisterCodeParam();
        checkRegisterCodeParam.setMachineId(machineId);
        CheckRegisterCodeVo checkRegisterCodeVo = registerCodeService.checkRegisterCode(checkRegisterCodeParam);
        if (checkRegisterCodeVo.getStatus() == RegisterCodeStatusEnum.EXPIRED.getCode()) {
            throw new BizException(SystemConstant.ResponseCode.NOT_AUTHORITY, "注册码已过期", checkRegisterCodeVo);
        }
        Video video = new Video();
        video.setMachineId(machineId);
        video.setVideoUrl(param.getVideoUrl());

        video.setSource(param.getSource());
        video.setQuality(param.getQuality());
        video.setStatus(VideoStatusEnum.NOT_PROCESS.getCode());


        String videoContent = param.getVideoContent();
        try {
            String titleStartStr = "name=\"title\" content=\"";
            String titleEndStr = "_哔哩哔哩_bilibili\"><meta";
            int titleStart = videoContent.indexOf(titleStartStr);
            int titleEnd = videoContent.indexOf(titleEndStr, titleStart);
            String title = videoContent.substring(titleStart + titleStartStr.length(), titleEnd).trim();
            video.setTitle(title);

        } catch (Exception e) {

        }
        try {

            //获取视频地址内容
            String searchStr = "window.__playinfo__=";
            int dataStart = videoContent.indexOf(searchStr);
            int dataEnd = videoContent.indexOf("</script>", dataStart);
            String subData = videoContent.substring(dataStart + searchStr.length(), dataEnd);
            JSONObject jsonObject = new JSONObject(subData);
            Integer resultCode = jsonObject.getInt("code");
            if (resultCode != 0) {
                throw new BizException("提交视频网页内容错误");
            }
            JSONObject dashJsonObj = jsonObject.getJSONObject("data").getJSONObject("dash");
            JSONArray videoJsonArray = dashJsonObj.getJSONArray("video");
            JSONArray audioJsonArray = dashJsonObj.getJSONArray("audio");
            for (int i = 0; i < videoJsonArray.size(); i++) {
                JSONObject videoJsonObj = videoJsonArray.getJSONObject(i);
                String id = videoJsonObj.get("id").toString();
                if (StringUtils.equalsIgnoreCase(param.getQuality(), id)) {
                    video.setVideoDownloadUrl(videoJsonObj.getStr("baseUrl"));
                    break;
                }
            }
            //如果没有，就取第一个
            if (StringUtils.isEmpty(video.getVideoDownloadUrl())) {
                String baseUrl = videoJsonArray.getJSONObject(0).getStr("baseUrl");
                video.setVideoDownloadUrl(baseUrl);
            }
            String baseUrl = audioJsonArray.getJSONObject(0).getStr("baseUrl");
            video.setAudioDownloadUrl(baseUrl);

            //保存
            this.save(video);

            //处理特殊字符标题，不做处理，中文全部乱码
//            String newTitle = UriUtils.encode(video.getTitle(), "UTF-8");
//            video.setTitle(newTitle);

        } catch (Exception e) {
            logger.error(videoContent);
            throw new BizException(e);
        }
        return video;

    }


}
